package com.zja.dao.Impl;

import com.zja.dao.BaseDAO;
import com.zja.dao.LikesDao;
import com.zja.model.Likes;

import java.util.List;

/**
 * @author JA
 */
public class LikesDaoImpl extends BaseDAO implements LikesDao {
    @Override
    public List<Likes> selectAll() {
        String sql = "SELECT * FROM likes";
        try {
            return executeQuery(Likes.class, sql);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Likes selectById(Long id) {
        String sql = "SELECT * FROM likes WHERE id = ?";
        try {
            return executeQueryBean(Likes.class, sql, id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean insert(Likes likes) {
        String sql = "INSERT INTO likes(user_id, article_id, created_at) VALUES(?, ?, ?)";
        try {
            return executeUpdate(sql, likes.getUserId(), likes.getArticleId(), likes.getCreatedAt());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean update(Likes likes) {
        String sql = "UPDATE likes SET user_id = ?, article_id = ?, created_at = ? WHERE id = ?";
        try {
            return executeUpdate(sql, likes.getUserId(), likes.getArticleId(), likes.getCreatedAt(), likes.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean deleteById(Long id) {
        String sql = "DELETE FROM likes WHERE id = ?";
        try {
            return executeUpdate(sql, id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //判断用户是否点赞
    @Override
    public boolean hasUserLiked(Long userId, Long articleId) {
        String sql = "SELECT COUNT(*) FROM likes WHERE user_id = ? AND article_id = ?";
        try {
            // 如果结果大于0，说明用户已经点赞过该文章
            return (Long) executeScalar(sql, userId, articleId) > 0;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //统计文章点赞数
    @Override
    public int countLikes(Long articleId) {
        String sql = "SELECT COUNT(*) FROM likes WHERE article_id = ?";
        try {
            return ((Long) executeScalar(sql, articleId)).intValue();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean deleteByUserAndArticle(Long userId, Long articleId) {
        String sql = "DELETE FROM likes WHERE user_id = ? AND article_id = ?";
        try {
            return executeUpdate(sql, userId, articleId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
